<?php
require_once('lib/Ecd.class.php');
class user extends common{
	private $companies_table = "companies";
	private $companies_detail_title_table = "companies_detail_title";
	private $companies_detail_table = "companies_detail";
	//获取验证码
	function getCode($param){
		extract($param);
		
		if(preg_match("/^1[34578]\d{9}$/",$phoneNumber)){
		//初始化
		$ecd = new Ecd( "http://www.etuocloud.com/gateway.action",'KP3e3CxLk2eldCTDFM0KP3QDLVq3B9Wl','wKhjBD1VtZkG4XWlVPIHW733u7kTPsfPCdQ3iwMuqaRCorqhlbV2KlN75mRvNUY1','xml');
		$code=str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
		$ecd->send_sms_code($phoneNumber,'1',$code,'');
		}else{
			$msg="手机号码格式不对";
			$error="1";
		}
		return array('code'=>$code);
	}
	//验证登录
	function login($param){
		extract($param);//使用数组键名作为变量名，使用数组键值作为变量值。
		
		$sql="users where phoneNumber='".$phoneNumber."'";
		$user=$this->getInfo($sql, 'id,password,userName');
		if($user['id']==''){
			$msg = '用户不存在';
			$error = '1';
		}else{
                        
			if($user['password']!=md5($password)){
				$msg = '密码错误';
				$error = '2';
			}else{
				$msg = '登录成功';
				$error = '0';
			}
		}
		return array('user_id'=>$user['id'],'userName'=>$user['userName'],'error'=>$error,'msg'=>$msg);
	}
	//找回密码
       function forgotPassword($param){
		extract($param);
                $data = array('password'=>md5($password));
                if($phoneNumber==false||$phoneNumber=='')
                {
                    return array('error'=>1,'msg'=>'请输入有效用户名');
                }
                $sql="users where phoneNumber='".$phoneNumber."'";
		$user=$this->getInfo($sql, 'id');
                if($user['id']==false||$user['id']=='')
                {
                    return array('error'=>1,'msg'=>'用户不存在');
                }
                else
                {
                    if($password==false||$password=='')
                    {
                         return array('error'=>1,'msg'=>'未输入密码');
                    }
                   else if($password!=$repassword)
                    {
                         return array('error'=>1,'msg'=>'两次输入的密码不一致');
                    }
                    else
                    {
                       $error =  $this->update('users',$data,"phoneNumber='".$phoneNumber."'");
                       if($error)
                       {
                           return array('error'=>0,'msg'=>'修改成功');
                       }
                       else{
                           return array('error'=>1,'msg'=>'修改失败');
                       }
                       
                    }
                }
               
       }
	 //获取注册信息
	function getregist($param){
		extract($param);
		if($id!="" && $id!=null){
		$sql1="users where id=$id";
		$result=$this->getInfo($sql1,$key="*");
		}
		return array('result'=>$result);;
	}
		
	//完善资料
	function additional($param){
		
		extract($param);
		//检验用户名是否存在
			$sql="users where id='".$id."'";
			$user=$this->getInfo($sql, 'id,userName');
			if($user['id']==''){
			   $msg='用户不存在';
			   $error='1';
		   }else{
			   //年龄验证
			   if(preg_match("/^([0-9]|[0-9]{2}|100)$/",$age)){ 
			   //身份证验证
			         if(preg_match("/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/",$card)){ 
					   //验证成功后更新插入到数据库
					    $arr = array('userName'=>$userName,'phoneNumber'=>$phoneNumber,'sex'=>$sex,'age'=>$age
					                                    ,'address'=>$address,'card'=>$card);
						$this->update('users',$arr,'id='.$id);
                                                $msg= $phoneNumber;
					 }else{
						 $msg="身份证格式不对";
						 $error="3";
					 }
			   }else{
				   $msg="年龄格式不对";
				   $error="2";
			   }
		   }
			return array('user_id'=>$user['id'],'error'=>$error,'msg'=>$msg);
	}
	
	//个人中心  
	//$id 为用户id
	//$id 为用户id
	function userCenter($param){
	        extract($param);
//                //余额
//		$balance;
//                //投资中资金
//        $investmentMoney;
//                //总收益
//        $accruedIncome;
//                //每月收益
//        $perMonthIncomes ;
//                 //
//                 $allMonths;
//		if($user_id!=""){
//		//获取余额
//		$key="balance";
//		$sql="users where id=".$user_id;
//		$result=$this->getInfo($sql, $key);
//		$balance = $result['balance'];
//		//投资中资金
//                $key="money";
//		$sql="user_investment where state = 1 and user_id=".$user_id;
//		$result=$this->getList($sql, $key);
//		if (is_array($result['result'])) {
//                    foreach ($result['result'] as $value) {
//                        $investmentMoney += $value['money'];
//                    }
//                }
//                //总收益
//                $key=" DATE_FORMAT(date,'%Y') as year,sum(income) as income";//一年中每月收益
//		$sql="user_income where  user_id=".$user_id." and DATE_FORMAT(date,'%Y')= ".date('Y')." group by year order by year";
//		$result=$this->getInfo($sql, $key);
//                $accruedIncome= $result['income'];
//                //每月收益
//                $key=" DATE_FORMAT(date,'%Y-%m') as month,sum(income) as income ";//一年中每月收益
//		$sql=" user_income where  user_id =".$user_id." and DATE_FORMAT(date,'%Y')= ".date('Y',  strtotime("-1 year"))." group by month order by month";	
//                $lastResult=$this->getList($sql, $key);
//                $key=" DATE_FORMAT(date,'%Y-%m') as month,sum(income) as income ";//一年中每月收益
//		$sql=" user_income where  user_id =".$user_id." and DATE_FORMAT(date,'%Y')= ".date('Y')." group by month order by month";	
//                $result=$this->getList($sql, $key);
//                $nowMonth = date('m');
//                $index = 0;
//                
//                if (intval($nowMonth)<6) {
//                    
//                      $startInt = 12-(6-intval($nowMonth))+1;
//                      for($x=$startInt; $x<= 12; $x++)
//                      {
//                          $allMonths[$index]=$x;
//                          $perMonthIncomes[$index]=@"0";
//                          $date = date('Y',  strtotime("-1 year"));
//                    
//                          if($x<10)
//                          {
//                                $date .= "-0".$x;
//                            foreach ($result['result'] as $key => $value) {
//                        
//                                if($date==$value['month'])
//                                 {
//                                 
//                                  $perMonthIncomes[$index] = $value['income'];
//                                  }
//                            } 
//                         }
//                         else
//                        {
//                             $date .= "-".$x;
//                            foreach ($result['result'] as $key => $value) {
//                                if($date==$value['month'])
//                                 {
//                                    
//                                 $perMonthIncomes[$index] = $value['income'];
//                                 }
//                            } 
//                        }
//                      $index++;
//                     }
//                      for($x=1; $x<= intval($nowMonth); $x++)
//                      {
//                        
//                          $date = date('Y');
//                          $allMonths[$index]=$x;
//                          $perMonthIncomes[$index]=@"0";
//                          if($x<10)
//                          {
//                                $date .= "-0".$x;
//                            foreach ($result['result'] as $key => $value) {
//                        
//                                if($date==$value['month'])
//                                 {
//                                 
//                                  $perMonthIncomes[$index] = $value['income'];
//                                  }
//                            } 
//                         }
//                         else
//                        {
//                             $date .= "-".$x;
//                            foreach ($result['result'] as $key => $value) {
//                                if($date==$value['month'])
//                                 {
//                                 $perMonthIncomes[$index] = $value['income'];
//                                 }
//                            } 
//                        }
//                     $index++;
//                     }
//                     
//                }
//                else
//                { //现在大于等于六月
//                      $perMonthIncomes = array();
//                      for($x=intval($nowMonth)+1-6; $x<= intval($nowMonth); $x++)
//                      {
//                          $date = date('Y');
//                          $allMonths[$index]=$x;
//                          $perMonthIncomes[$index]=@"0";//初始化数组当前索引下的数值  $perMonthIncomes[$index]=@"0";
//                          if($x<10)
//                          {
//                                $date .= "-0".$x;
//							if($result['result']!='' && $result!=null){
//								foreach ($result['result'] as $key => $value) {
//							
//									if($date==$value['month'])
//									 {
//								
//									  $perMonthIncomes[$index] = $value['income'];
//									  }
//								} 
//							}
//                         }
//                         else
//                        {
//                             $date .= "-".$x;
//                            foreach ($result['result'] as $key => $value) {
//                                if($date==$value['month'])
//                                 {
//                                 $perMonthIncomes[$index] = $value['income'];
//                                 }
//                            } 
//                        }
//                      $index++;
//                     }
//                }
               
                
//               
//		return array('result'=>array('totalAssets'=>$balance+$investmentMoney,'balance'=>$balance,'accruedIncome'=>$accruedIncome,'investmentMoney' => $investmentMoney,'perMonthIncomes'=>$perMonthIncomes,'allMonths'=> $allMonths),error=>'0','msg'=>'成功');
//		}else{
//			$msg="未检测到用户";
//			$error="1";
//                        return array(error=>$error,'msg'=>$msg);
//		}
		if($user_id!=""){
		
		$key="*";
		$sql="users where id=".$user_id;
		$result=$this->getInfo($sql, $key);
		return array('result'=>$result) ;
                }
		
	}	
private $table_name="user_investment"; 
	//取消收藏
        function  getCollectState($param) {
          extract($param);
		  //去数据库查询此用户是否已经收藏
			$sql=$this->table_name." where user_id=$userid and company_id=$companyid and state=4";
			$result=$this->getInfo($sql);
			if($result['state']==4){		
					return array('msg'=>$msg,'error'=>$error,'state'=>'4');
			}else{
				    return array('msg'=>$msg,'error'=>$error,'state'=>'0');
			}
        }

	function collect($param){
		extract($param);
		if($userid!="" && $companyid!=null){
			//去数据库查询此用户是否已经收藏
			$sql=$this->table_name." where user_id=$userid and company_id=$companyid and state=4";
			$result=$this->getInfo($sql);
			if($result!="" && $result!=null){
				$msg="已经取消对该公司的收藏";
				$error="1";
				/*$datas=array('state'=>'4');
				$this->update($this->table_name,$datas,"company_id=$companyid");*/
				$sqls="delete from user_investment where user_id=$userid and company_id=$companyid and state=4";
				$resu = $this->query($sqls);
				
			}else{
				$msg="收藏成功";
				$error="0";
				$data = array('user_id'=>"$userid",'company_id'=>"$companyid",'state'=>4,'click_date'=>date('Y-m-d',time()));
				$res=$this->insert($this->table_name,$data);	
			}
		}
		return array('msg'=>$msg,'error'=>$error,'state'=>$data['state']);
	}
		  //收藏列表//更新
        function collectList($param){
		
		extract($param);
		if($user_id!=""){
                  $sql = "user_investment u left join users us on u.user_id=us.id  left join companies c on u.company_id=c.id   where  u.state = 4 and u.user_id = ".$user_id;
                  $key = "u.id,u.company_id,u.click_date,us.balance,c.title as companyName ,c.star";
                  $list1 =$this->getList($sql,$key, $num, $page);
            
                  if(is_array($list1['result']))
                  {
                    
                    foreach ($list1['result'] as $k => $value) 
                        {
                         if($value['company_id'])
                            {
                             $sql  = "companies_detail_title cdt left join companies_detail cd on cdt.id = cd.title_id and cd.company_id = ".$value['company_id']." where   cdt.id=7 or cdt.id=8 or cdt.id=6";
                             $key = "cdt.id_marking, cd.content";
                             $list2 =$this->getList($sql, $key);
			
			if(is_array($list2['result']))
                        {      
				foreach( $list2['result'] as $key=>$val)
                                { 
					$list1['result'][$k][$val['id_marking']] = $val['content'];
                                      
				}
                                
			}
		      }
                     }
                   }
                  
		return array('list'=>$list1['result'],'error'=>'0','msg'=>'请求成功');
		}else{
			return array('error'=>'1','msg'=>'请求失败');
		}
	}
        //卖出
         function  sale($param) {
            extract($param);
             //插入数据库
          $data = array('state'=>'2');
          $result = $this->update('user_investment', $data, "id='".investment_id."'");
          if($result)
          {
               return array('error'=>'0','msg'=>'成功');
          }
          else
          {
               return array('error'=>'1','msg'=>'失败');
          }
        }
        //投资'user_id'=>'','company_id'=>'','date'=>'','value_date'=>'','date_came'=>''
        function investment($param) {
                 extract($param);
                 $sql="user_investment where user_id = " .$user_id." and company_id = ".$company_id ;
                 $result=$this->getInfo($sql,'id');
                 if($result['id'])
                 {
                      $data = array('money'=>$money,'date'=>$date,'value_date'=>$value_date,'date_came'=>$date_came,'state'=>'1');
                      $result = $this->update('user_investment', $data, "id= ".$result['id']);
                 }
                else
                 {
                      $data = array('user_id'=>$user_id,'company_id'=>$company_id,'money'=>$money,'date'=>$data,'value_date'=>$value_date,'date_came'=>$date_came);
                      $this->insert('user_investment',$data);
                      $id = $this->insert_id();
	              $data = array('sort'=>$id);
                      $result = $this->update('user_investment', $data, "id='".$id."'");
                 }   
                 if($result)
                 {
                   return array('error'=>'0','msg'=>'成功');
                 }
                  else
                 {
                   return array('error'=>'1','msg'=>'失败');
                 }
        }
	/*我的投资列表//更新
         * state:0收藏、1投资、2卖出
        */
	function investmentList($param){
		
		extract($param);
		if($user_id!=""){
                  $sql = "user_investment u  left join company_product cp on u.product_id = cp.id  left join companies c on cp.company_id=c.id    where  u.state = 1 and u.user_id = ".$user_id;
                  $key = "u.id,u.company_id,u.money,u.date_buy,u.buy_num, u.trade_successful , cp.name,cp.price,cp.img_0 as imageName,c.title as companyName ,c.star";
                  $list1 =$this->getList($sql,$key, $num, $page);
            
//                  if(is_array($list1['result']))
//                  {
//                    
//                    foreach ($list1['result'] as $k => $value) 
//                        {
//                         if($value['company_id'])
//                            {
//                             $sql  = "companies_detail_title cdt left join companies_detail cd on cdt.id = cd.title_id and cd.company_id = ".$value['company_id']." where   cdt.id=7 or cdt.id=8";
//                             $key = "cdt.id_marking, cd.content";
//                             $list2 =$this->getList($sql, $key);;
//			
//			if(is_array($list2['result']))
//                        {      
//				foreach( $list2['result'] as $key=>$val)
//                                { 
//					$list1['result'][$k][$val['id_marking']] = $val['content'];
//                                      
//				}
//                                
//			}
//		      }
//                     }
//                   }
                  
		return array('list'=>$list1['result'],'error'=>'0','msg'=>'请求成功');
		}else{
			return array('error'=>'1','msg'=>'请求失败');
		}
	}
	//投资详情//更新
	//$investment_id 投资id
	function investmentDeltail($param){
		
		extract($param);
		
		if($investment_id!=''){
                $sql = "user_investment u left join companies c on u.company_id=c.id   where u.id = ".$investment_id;
                $key = "u.id,u.company_id,u.money,u.value_date,u.date_came,u.date,c.title as companyName ,c.star";
	        $result=$this->getInfo($sql,$key);
               
		if( $result)
                            {
                             $sql  = "companies_detail_title cdt left join companies_detail cd on cdt.id = cd.title_id and cd.company_id = ".$result['company_id'];
                             $key = "cdt.id_marking, cd.content";
                             $list2 =$this->getList($sql, $key);;
			
			if(is_array($list2['result']))
                        {      
				foreach( $list2['result'] as $key=>$val)
                                { 
					$result[$val['id_marking']] = $val['content'];
                                      
				}
                                
			}
	
		}
		return array('result'=>$result,'error'=>'0','msg'=>'成功');
	}
     } 

     
     //账户余额、$user_id用户ID
     function accountBalance($param){
		extract($param);//使用数组键名作为变量名，使用数组键值作为变量值。
		
		$sql="users where id = ".$user_id;
		$user=$this->getInfo($sql, 'balance');
                var_dump($sql);
		return array('result'=>$user,'error'=>$error,'msg'=>$msg);
	}
        //
        function  payToAccount($param) {
            extract($param);//使用数组键名作为变量名，使用数组键值作为变量值。
             //检验银行卡号
            if( !preg_match('/^\d+$/i', $payMoney)){return array('error'=>'1','msg'=>'不是纯数字');}
	    $sql="users where id = ".$user_id;
	    $user=$this->getInfo($sql, 'balance');
            $money = $user['balance']+$payMoney;
            $data = array('balance'=>$money );
            $result = $this->update('users', $data, "id='".$user_id."'");
            if($result)
            {
              $user=$this->getInfo($sql, 'balance');
               return array('result'=>$user,'msg'=>'成功');
            }
            else
            {
               return array('error'=>'1','msg'=>'失败');
            }
        }   
      /*添加银行卡号
       * user_id int,bank_name 字符串,card_no 字符串,card_no 字符串,IDName 字符串,IDCardNo 字符串
       */
      function addBankCard($param) {
          extract($param);
          $error = 0;
          $card_no = preg_replace("/ /","",$card_no);//去除空格
          //检验银行卡号
          if( !preg_match('/^\d+$/i', $card_no)){return array('error'=>'1','msg'=>'银行卡号不是纯数字');}
          //插入数据库
          $data = array('user_id'=>$user_id,'bank_name'=>$bank_name,'card_no'=>$card_no,'IDName'=>$IDName,'IDCardNo'=>$IDCardNo);
          $this->insert('user_bankcard',$data);
          $id = $this->insert_id();
	  $data = array('sort'=>$id);
         $result = $this->update('user_bankcard', $data, "id='".$id."'");
          if($result)
          {
              return array('error'=>'0','msg'=>'成功');
          }
          else
          {
               return array('error'=>'1','msg'=>'失败');
          }
      }
	  
	    /*获取银行卡列表
       * 
       */
      function bankCardList($param) {
          extract($param);
          $error = 0;
          $sql = "user_bankcard  where user_id = ".$user_id;
          $list1 =$this->getList($sql);
          if($list1["result"])
          {
              return array('list'=>$list1["result"],'error'=>'0','msg'=>'成功');
          }
          else
          {
               return array('error'=>'1','msg'=>'失败');
          }
      }

	  //提现
	   function  cashToAccount($param) {
				extract($param);//使用数组键名作为变量名，使用数组键值作为变量值。
			if( !preg_match('/^\d+$/i', $cashMoney)){return array('error'=>'1','msg'=>'不是纯数字');}
			$sql="users where id = ".$user_id;
			$user=$this->getInfo($sql, 'balance');
			if($user['balance']!='' && $user['balance']!=null && $user['balance']>$cashMoney){
				$money = $user['balance']-$cashMoney;
				$data = array('balance'=>$money );
				$result = $this->update('users', $data, "id='".$user_id."'");
				if($result)
				{
				  $user=$this->getInfo($sql, 'balance');
				   return array('result'=>$user,'msg'=>'成功');
				}else{
				   return array('error'=>'1','msg'=>'失败');
				}
			}else{
				return array('error'=>'1','msg'=>'失败');
			}
        } 
	//app意见的反馈	
		function getFeedBack($param){
			extract($param);
			if($user_id!="" && $user_id!=null){
				//判断用户是否存在
				$sql="users where id=".$user_id;
				$user=$this->getInfo($sql);
				if($user!='' && $user!=null){
					//判断用户是否已经反馈过问题
					$sqls="user_feed_back where user_id=".$user_id;
				    $res=$this->getInfo($sqls);
					if($res!='' && $res!=null){
						$data = array('user_id'=>$user_id,'content'=>$content,'back_date'=>date("y-m-d H:i:s",time()));
						$this->update("user_feed_back",$data,"id='".$res['id']."'");
						return array('error'=>$error,'msg'=>$msg);
					}else{
						$data = array('user_id'=>$user_id,'content'=>$content,'back_date'=>date("y-m-d H:i:s",time()));
						$this->insert('user_feed_back',$data);
						return array('error'=>$error,'msg'=>$msg);
					}
				}else{
					$msg="不存在此用户";
					$error="1";
					return array('msg'=>$msg,'error'=>$error);
				}
			}
			
		}
	//获取客服信息
	function getService($param){
		extract($param);
		$sql="service order by id DESC";
		$result=$this->getInfo($sql);
		return $result;
		
	}
	
	
	//用户举报	
		function userReport($param){
		  $apic = newInstance('service'); 
	       $arr1=$apic->log($_POST);
	       $arr=$apic->log($_FILES);
 
                extract($param);
		   //上传图片，生成缩略图
		if($_FILES['file0']['name']!=''){
			//设置路径
			//$folder= $GLOBALS['common']['imgPath']."upload/image/";
			$folder="upload/report/";
			$annexFolder = $folder."large/";
			$middleFolder = $folder."middle/";
			$smallFolder = $folder."small/";
			//删除旧图
			@unlink($annexFolder.$img);
			@unlink($middleFolder.$img);
			@unlink($smallFolder.$img);
                         $arr=$apic->log('上传');
			//上传新图
			$upimg = newInstance('uploadImg');
                      
			$img = $upimg->upLoad('file0',$annexFolder);
              
			//中图
			$upimg->smallImg($annexFolder.$img,$middleFolder);
			//小图
			$upimg->smallImg($annexFolder.$img,$smallFolder);
		}

			if($user_id!="" && $user_id!=null){
				//判断用户是否存在
				$sql="user_reported where id=".$user_id;
				$user=$this->getInfo($sql);
					//判断用户是否已经举报过
					$sqls="user_reported where user_id=".$user_id." and company_id=".$company_id;
				    $res=$this->getInfo($sqls);
						$data = array('user_id'=>$user_id,'img'=>$img,'company_id'=>$company_id,'content'=>$content,'data'=>date("y-m-d H:i:s",time()));
						$this->insert('user_reported',$data);
						return array('error'=>$error,'msg'=>$msg);	
			}
			
		}
		
	
    /*获取用户所属的群组
	*@param $userid 用户注册的电话号
	*/
	function getUserGroup($param){
		extract($param);
		if($userId!='' && $userId!=null){
			$sqls="group_user u left join  group_create c on u.group_id = c.group_id left join companies i on c.company_id=i.id   where user_id=".$userId;
			$result=$this->getList($sqls,"c.group_name,u.group_id,i.title");
			return $result;
		}
	}
	
	 /*获取用户举报的公司
	*@param $userid 用户id
	*/
	function getUserReport($param){
		extract($param);//group by companyId
		if($userid!='' && $userid!=null){
			$sql="user_reported u left join companies c on u.company_id=c.id where u.user_id='".$userid ."' group by companyId" ;
			$res=$this->getList($sql,$key="c.title,c.img,c.star,u.company_id as companyId");
			if($res['result']!='' && $res['result']!=null){
			foreach($res['result'] as $val){
			}
			}
			if($val['title']!='' && $val['title']!=null){
					if(is_array($res['result'])){
						foreach($res['result'] as $k=>$v){
							//var_dump($v['company_id']);
							$sql = $this->companies_detail_table." d
									left join ".$this->companies_detail_title_table." t on d.title_id=t.id
									where d.company_id='".$v['companyId']."'";
									//var_dump($sql);
							$info = $this->getList($sql,'t.id_marking,d.content');
							if(is_array($info['result'])){
								foreach($info['result'] as $key=>$val){
									$v[$val['id_marking']] = $val['content'];
								}
							}

							$res['result'][$k] = $v;
							
						}
					}
					return $res;
			    }
		    }
		}

		
	//获取用户举报列表
	function getUserReportDetail($param){
	     extract($param);
		 if($userid!='' && $companyid!=null){
			 $sql="user_reported where user_id=".$userid." and company_id=".$companyid;
			 $res=$this->getList($sql,$key='content,img,data,id');
			 return $res;
		 }
	}
	
	//获取举报的列表
	function getReportList($param){
	     extract($param);
		 if($user_id!='' && $user_id!=null){
			 $sql="user_reported r left join companies c on r.company_id=c.id where r.user_id=".$user_id;
			 $res=$this->getList($sql, $key="r.*,c.title,c.img", $num, $page);
			 return $res;
			// print_r($res);
		 }
	}
	//举报详情
	function getReport($param){
	     extract($param);
		 if($id!='' && $id!=null){
			 $sql="user_reported where id=".$id;
			 $res=$this->getInfo($sql);
			 return $res;
		 }
	}
}  



